package com.hengda.smart.speak.d.fragment;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.media.AudioManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.hengda.smart.speak.d.App;
import com.hengda.smart.speak.d.R;
import com.hengda.smart.speak.d.base.BaseFragment;
import com.hengda.smart.speak.d.bean.ExhibitInfo;
import com.hengda.smart.speak.d.bean.UnitInfo;
import com.hengda.smart.speak.d.config.AppConfig;
import com.hengda.smart.speak.d.config.DataBaseUtil;
import com.hengda.smart.speak.d.config.DbConfig;
import com.hengda.smart.speak.d.db.ResourceDb;
import com.hengda.smart.speak.d.dialog.HDMediaBuilder;
import com.hengda.smart.speak.d.media.MediaConstant;
import com.hengda.smart.speak.d.service.RecorderService;
import com.hengda.smart.speak.d.state.StateConstantAction;
import com.hengda.smart.speak.d.stc.ControlService;
import com.hengda.smart.speak.d.stc.LancherConstant;
import com.hengda.smart.speak.d.stc.StcLauncher;
import com.hengda.smart.speak.d.util.SharePreferenceUtil;
import com.hengda.smart.speak.d.util.ToastUtil;
import com.jaredrummler.materialspinner.MaterialSpinner;
import com.nikhilpanju.recyclerviewenhanced.OnActivityTouchListener;
import com.nikhilpanju.recyclerviewenhanced.RecyclerTouchListener;

import org.adw.library.widgets.discreteseekbar.DiscreteSeekBar;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class AreaFragment extends BaseFragment implements RecyclerTouchListener.RecyclerTouchListenerHelper {

    RecyclerView rv_play;
    MainAdapter mAdapter;
    private RecyclerTouchListener onTouchListener;
    private OnActivityTouchListener touchListener;

    MaterialSpinner msp_search;
    DiscreteSeekBar seekBar_volume;

    private AudioManager audioManager;
    private Intent serviceIntent;

    private List<ExhibitInfo> rsInfoList = new ArrayList<ExhibitInfo>();
    private List<ExhibitInfo> newDataList = new ArrayList<ExhibitInfo>();
    private List<UnitInfo> unitInfoList = new ArrayList<UnitInfo>();
    private List<String> unitNameList = new ArrayList<String>();
    //展线展示数据
    private Cursor unitCursor;

    private ExhibitInfo rsInfo;

    //工具类
    private SharePreferenceUtil spUtil; //偏好设置
    private StcLauncher lancherUtil;    //STC发送工具

    private Intent 	playIntent;
    private IntentFilter intentFilter;

    private int duration ;
    private int playPosition;
    //音频布局
    private HDMediaBuilder mediaDialog;
    //private 切换语音
    private boolean changeNewVideo=false;

    private boolean  playFlag=false;
    private boolean  playComFlag=false;
    private boolean pauseFlag=false;

    public static AreaFragment newInstance() {
        Bundle args = new Bundle();
        AreaFragment fragment = new AreaFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_area, container, false);
        initViews(view);
        initUtil();
        initDatasAndListener();
//        initBroadCast();
        return view;
    }

    private BroadcastReceiver receiver=new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(MediaConstant.MUSIC_DURATION)){
                duration=intent.getIntExtra(MediaConstant.FILELD_DURATION, 0);
                if(mediaDialog.isShowing()){
                    duration /= 1000;
                    int minute =duration / 60;
                    int second = duration % 60;
                    minute %= 60;
                    mediaDialog.setSeekbarMax(duration);
                    mediaDialog.setDuration(String.format("%02d:%02d", minute, second));
                }
            }

            if(intent.getAction().equals(MediaConstant.MUSIC_CURRENT)){
                playPosition=intent.getIntExtra(MediaConstant.FILELD_CURRENT, 0);
                if(mediaDialog.isShowing()){
                    if(changeNewVideo){

                    }else{
                        playPosition /= 1000;
                        int minute = playPosition / 60;
                        // int hour = minute / 60;
                        int second = playPosition % 60;
                        minute %= 60;
                        mediaDialog.setSeekPosition(playPosition);
                        mediaDialog.setHasPlay(String.format("%02d:%02d", minute,
                                second));
                    }
                }
            }

            if(intent.getAction().equals(MediaConstant.MUSIC_PLAY_COM)){
                playPosition=0;
                if(mediaDialog.isShowing()){
                    mediaDialog.setPlayBarBg(R.mipmap.control_play);
                    mediaDialog.setHasPlay("0.00");
                    mediaDialog.setSeekPosition(playPosition);
                }
                playFlag=false;
                playComFlag=true;
            }

            if(intent.getAction().equals(ControlService.ACTION_REICEIVE_RFID)){
                clearCurrentMedia();
            }

        }
    };

    private void clearCurrentMedia() {

        if(mediaDialog.isShowing()){
            mediaDialog.dismiss();
        }

        if(rsInfo!=null){
            playIntent.putExtra("url",DbConfig.BASE_PATH	+ rsInfo.getFilePath()+File.separator
                    + rsInfo.getFileNo()+"."+rsInfo.getType());
            playIntent.putExtra("MSG", MediaConstant.MSG.PAUSE_MSG);
            getActivity().startService(playIntent);
            pauseFlag=true;
            mediaDialog.setPlayBarBg(R.mipmap.control_play);
            playPosition=0;
            playComFlag=true;
            playFlag=false;
            pauseFlag=true;
            changeNewVideo=true;
        }
    }


    private void initBroadCast() {
        //广播监听过滤器
        intentFilter=new IntentFilter();
        intentFilter.addAction(MediaConstant.MUSIC_DURATION);
        intentFilter.addAction(MediaConstant.MUSIC_CURRENT);
        intentFilter.addAction(MediaConstant.MUSIC_PLAY_COM);
        intentFilter.addAction(LancherConstant.BROADCAST_AUDIO_SUCCESS);
        intentFilter.addAction(LancherConstant.BROADCAST_AUDIO_FAILURE);
        intentFilter.addAction(LancherConstant.BROADCAST_INFRARED_CHANNEL);
        intentFilter.addAction(LancherConstant.ACTION_CHANGE_HOST);
        intentFilter.addAction(ControlService.ACTION_REICEIVE_RFID);
        getActivity().registerReceiver(receiver, intentFilter);
    }

    private void initDatasAndListener() {
        playIntent = new Intent(MediaConstant.MUSIC_PLAY_ACTION);// 发送播放服务

        lancherUtil = new StcLauncher(App.getInstance(), getActivity());
        spUtil = new SharePreferenceUtil(getActivity(), AppConfig.SHARE_NAME);
        seekBar_volume.setOnProgressChangeListener(new DiscreteSeekBar.OnProgressChangeListener() {

            @Override
            public void onStopTrackingTouch(DiscreteSeekBar seekBar) {
            }

            @Override
            public void onStartTrackingTouch(DiscreteSeekBar seekBar) {
            }

            @Override
            public void onProgressChanged(DiscreteSeekBar seekBar, int value,
                                          boolean fromUser) {
                spUtil.setChannelVolume(value);
                changeVolume();
                getActivity().sendBroadcast(new Intent(StateConstantAction.ACTION_CHANGE_VOLUME));
            }

        });
        seekBar_volume.setProgress(spUtil.getChannelVolume());


        unitCursor = ResourceDb.get_instance().getUnitList(DbConfig.TABLE_UNIT);
        if (unitCursor != null) {
            unitInfoList = DataBaseUtil.getUnitList(unitCursor);
            if (unitNameList.size() > 0) {
                unitNameList.clear();
            }
            for (int i = 0; i < unitInfoList.size(); i++) {
                unitNameList.add(unitInfoList.get(i).getUnitNameMain());
            }
        } else {
            ToastUtil.showToast(_mActivity, "无数据资源！");
            unitNameList.add("无数据资源");
        }
        msp_search.setItems(unitNameList);

        //==如果名字集合不为空，则默认显示第一个集合里面的值
        if (unitInfoList.size() > 0) {
            rsInfoList.addAll(DataBaseUtil.getRsInfoList(ResourceDb.get_instance().getRsInfoListByUnit(DbConfig.TABLE_INFO, unitInfoList.get(0).getUnitNo())));
            mAdapter = new MainAdapter(_mActivity, rsInfoList);
            rv_play.setAdapter(mAdapter);
            rv_play.setLayoutManager(new LinearLayoutManager(_mActivity));
        }
    }

    private void changeVolume() {
        lancherUtil.openAudio(spUtil.getHostNo(), spUtil.getChannelVolume());
        getActivity().sendBroadcast(new Intent(StateConstantAction.ACTION_CHANGE_VOLUME));
    }


    @Override
    public void onResume() {
        super.onResume();
        rv_play.addOnItemTouchListener(onTouchListener);
    }

    @Override
    public void onPause() {
        super.onPause();
        rv_play.removeOnItemTouchListener(onTouchListener);
    }

    private void initViews(View view) {
        rv_play = (RecyclerView) view.findViewById(R.id.rv_play);
        msp_search = (MaterialSpinner) view.findViewById(R.id.msp_search);
        seekBar_volume = (DiscreteSeekBar) view.findViewById(R.id.seekBar_volume);
        //spinner

        msp_search.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {

            @Override
            public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
//                Snackbar.make(view, "Clicked " + item, Snackbar.LENGTH_LONG).show();
                ToastUtil.showToast(_mActivity, "Clicked " + item);

            }
        });
        onTouchListener = new RecyclerTouchListener(_mActivity, rv_play);
        onTouchListener
                .setSwipeOptionViews(R.id.edit, R.id.change)
                .setSwipeable(R.id.rowFG, R.id.rowBG, new RecyclerTouchListener.OnSwipeOptionsClickListener() {
                    @Override
                    public void onSwipeOptionClicked(int viewID, int position) {
                        String message = "";
                        if (viewID == R.id.edit) {
                            message += "Add";
                        } else if (viewID == R.id.change) {
                            message += "Edit";
                        }
                        message += " clicked for row " + (position + 1);
//                        ToastUtil.makeToast(getApplicationContext(), message);
                        rsInfo = rsInfoList.get(position);
                        playRsMedia(rsInfo);
                        ToastUtil.showToast(_mActivity, message);
                    }
                });
    }

    private void initUtil() {
        lancherUtil=new StcLauncher(App.getInstance(),getActivity());
        spUtil=new SharePreferenceUtil(getActivity(), AppConfig.SHARE_NAME);
        audioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
        serviceIntent= new Intent(getActivity(),RecorderService.class);
    }

    @Override
    public void setOnActivityTouchListener(OnActivityTouchListener listener) {
        this.touchListener = listener;
    }

    private class MainAdapter extends RecyclerView.Adapter<MainAdapter.MainViewHolder> {
        LayoutInflater inflater;
        List<ExhibitInfo> modelList;

        public MainAdapter(Context context, List<ExhibitInfo> list) {
            inflater = LayoutInflater.from(context);
            modelList = new ArrayList<>(list);
        }

        @Override
        public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = inflater.inflate(R.layout.item_rv_play, parent, false);
            return new MainViewHolder(view);
        }

        @Override
        public void onBindViewHolder(MainViewHolder holder, int position) {
            holder.bindData(modelList.get(position), position);
        }

        @Override
        public int getItemCount() {
            return modelList.size();
        }

        class MainViewHolder extends RecyclerView.ViewHolder {

            TextView mainText, subText;

            public MainViewHolder(View itemView) {
                super(itemView);
                mainText = (TextView) itemView.findViewById(R.id.mainText);
                subText = (TextView) itemView.findViewById(R.id.subText);
            }

            public void bindData(ExhibitInfo rowModel, int position) {
                mainText.setText(position + "");
                subText.setText(rowModel.getFileName());
            }
        }
    }

    private void playRsMedia(ExhibitInfo info) {
        playIntent.putExtra("url",DbConfig.BASE_PATH	+ rsInfo.getFilePath()+ File.separator
                + rsInfo.getFileNo()+"."+rsInfo.getType());
        playIntent.putExtra("MSG", MediaConstant.MSG.PLAY_MSG);
        getActivity().startService(playIntent);
    }


}
